/*
 *
 *      Copyright (c) 2018-2025, cloud All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the pig4cloud.com developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: cloud
 *
 */

package com.fuyao.cloud.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuyao.cloud.admin.api.entity.*;
import com.fuyao.cloud.admin.api.vo.EgdUserInfoVO;
import com.fuyao.cloud.admin.constant.UserConstants;
import com.fuyao.cloud.admin.mapper.*;
import com.fuyao.cloud.admin.service.EgdUserInfoService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 * 部门管理 服务实现类
 * </p>
 *
 * @author cloud
 * @since 2018-01-20
 */
@Service
@Slf4j
@AllArgsConstructor
public class EgdOrgUserInfoServiceImpl extends ServiceImpl<EgdOrgUserinfoMapper, EgdOrgUserinfo> implements EgdUserInfoService {

    private final EgdOrgUserinfoMapper egdOrgUserinfoMapper;
    private final EgdOrgJobtitleMapper jobTitleMapper;
    private final SysUserinfoMapper userinfoMapper;
    private final SysUserMapper userMapper;
    private final SysDeptMapper deptMapper;
    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    @Override
    public boolean syncOaUserInfoToUser() {
        List<EgdUserInfoVO> userInfoVOList = egdOrgUserinfoMapper.selectUserInfoList();
        AtomicReference<SysUser> tempUser = new AtomicReference<>(new SysUser());

        userInfoVOList.forEach(egdUserInfoVO -> {
            SysUser sysUser = userMapper.selectByLoginName(egdUserInfoVO.getLoginName());

            // 处理所属单位
            List<SysDept> deptList = deptMapper.getDeptByFullCode(egdUserInfoVO.getOuFullCode());

            if (ObjectUtil.isNotEmpty(sysUser)) {
                tempUser.set(sysUser);
                if(StrUtil.isEmpty(sysUser.getUsername())){
                    sysUser.setUsername(egdUserInfoVO.getLoginName());
                }else{
                    sysUser.setName(egdUserInfoVO.getUserName());
                    sysUser.setNickname(egdUserInfoVO.getUserName());
                }
                sysUser.setPhone(egdUserInfoVO.getMobile());
                sysUser.setDelFlag((egdUserInfoVO.getUserStatus().equals(0) ? "0" : "1"));
                sysUser.setUpdateTime(LocalDateTime.now());
                if (CollUtil.isNotEmpty(deptList)) {
                    SysDept sysDept = CollUtil.getFirst(deptList);
                    sysUser.setDeptId(sysDept.getDeptId());
                    sysUser.setDeptName(sysDept.getFullName());
                }
                this.userMapper.updateUser(sysUser);
            } else {
                SysUser userNew = new SysUser();
                userNew.setUsername(egdUserInfoVO.getLoginName());
                userNew.setName(egdUserInfoVO.getUserName());
                userNew.setNickname(egdUserInfoVO.getUserName());
                userNew.setPhone(egdUserInfoVO.getMobile());
                userNew.setCreateTime(LocalDateTime.now());
                userNew.setLockFlag("0");
                userNew.setPassword(ENCODER.encode(UserConstants.DEFAULT_PASSWORD));
                if (CollUtil.isNotEmpty(deptList)) {
                    SysDept sysDept = CollUtil.getFirst(deptList);
                    userNew.setDeptId(sysDept.getDeptId());
                    userNew.setDeptName(sysDept.getFullName());
                    userNew.setTenantId(sysDept.getTenantId());
                }
                this.userMapper.insert(userNew);
                tempUser.set(userNew);
            }

            // 用户信息
            SysUserinfo sysUserinfo = CollUtil.getFirst(this.userinfoMapper.selectList(Wrappers.<SysUserinfo>query().lambda().eq(SysUserinfo::getPersonNumber, egdUserInfoVO.getPersonNumber())));
            if (ObjectUtil.isNotEmpty(sysUserinfo)) {
                SysUserinfo updateUserInfo = getSysUserInfo(sysUserinfo, egdUserInfoVO);
                updateUserInfo.setUserId(tempUser.get().getUserId());
                updateUserInfo.setDeptId(tempUser.get().getDeptId());
                updateUserInfo.setDeptFullname(tempUser.get().getDeptName());
                this.userinfoMapper.updateUserInfo(updateUserInfo);
            } else {
                SysUserinfo sysUserinfoNew = new SysUserinfo();
                SysUserinfo saveUserInfo = getSysUserInfo(sysUserinfoNew, egdUserInfoVO);
                saveUserInfo.setUserId(tempUser.get().getUserId());
                saveUserInfo.setDeptId(tempUser.get().getDeptId());
                saveUserInfo.setDeptFullname(tempUser.get().getDeptName());

                saveUserInfo.setCreateTime(LocalDateTime.now());
                saveUserInfo.setCreateId(tempUser.get().getUserId());
                saveUserInfo.setCreateBy(tempUser.get().getUsername());
                saveUserInfo.setTenantId(tempUser.get().getTenantId());
                this.userinfoMapper.insert(saveUserInfo);
            }
        });
        log.info("同步用户信息成功:{}", LocalDateTime.now());
        return Boolean.TRUE;
    }

    @Override
    public void insertEgdOrgUserinfo(EgdOrgUserinfo orgUserinfo) {
        this.egdOrgUserinfoMapper.insertEgdOrgUserinfo(orgUserinfo);
    }

    @Override
    public void updateByIdAndUnid(EgdOrgUserinfo orgUserinfo) {
        this.egdOrgUserinfoMapper.updateByIdAndUnid(orgUserinfo);
    }

    /**
     * 处理用户信息属性赋值
     *
     * @param sysUserinfo   用户信息对象
     * @param egdUserInfoVO oa用户视图对象
     * @return 用户信息
     */
    private SysUserinfo getSysUserInfo(SysUserinfo sysUserinfo, EgdUserInfoVO egdUserInfoVO) {
        sysUserinfo.setUpdateTime(LocalDateTime.now());
        sysUserinfo.setName(egdUserInfoVO.getUserName());
        sysUserinfo.setBirthday(egdUserInfoVO.getBirthday());
        sysUserinfo.setTelephone(egdUserInfoVO.getTelephoneno());
        sysUserinfo.setCardId(egdUserInfoVO.getCardId());
        sysUserinfo.setFaxno(egdUserInfoVO.getFaxno());
        sysUserinfo.setLoginname(egdUserInfoVO.getLoginName());
        sysUserinfo.setMobile(egdUserInfoVO.getMobile());
        sysUserinfo.setEmail(egdUserInfoVO.getEmail());
        sysUserinfo.setGender(StrUtil.emptyToDefault(egdUserInfoVO.getGender(), "0"));
        sysUserinfo.setPersonNumber(egdUserInfoVO.getPersonNumber());
        sysUserinfo.setStatus(String.valueOf(egdUserInfoVO.getUserStatus()));

        EgdOrgJobtitle jobTitle = jobTitleMapper.selectById(egdUserInfoVO.getJobTitleId());
        sysUserinfo.setPost(jobTitle.getName());
        sysUserinfo.setType(egdUserInfoVO.getUserType());
        return sysUserinfo;
    }
}
